<?php
/**
 * I know no such things as genius,it is nothing but labor and diligence.
 *
 * @copyright (c) 2015~2019 xinran All rights reserved.
 * @author 晋<657306123@qq.com>
 */

namespace app\admin\controller;

use app\admin\Controller;
use app\common\facade\View;
use app\common\model\Setting as SettingModel;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\facade\Config;
use think\facade\Url;
use Xin\Support\Arr;
use Xin\Support\Str;
use Xin\Thinkphp5\Controller\CURD;

/**
 * 配置控制器
 */
class SettingController extends Controller{

	use CURD;

	/**
	 * 配置管理
	 *
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
	public function index(){
		$keywords = $this->request->keywordsSql();
		$data = SettingModel::when(!empty($keywords), function(Query $query) use ($keywords){
			$query->where('title|name', 'like', $keywords);
		})->order('id desc')->paginate($this->request->limit(), false, [
			'page'  => $this->request->page(),
			'query' => $this->request->get(),
		]);
		$this->assign('data', $data);
		return View::fetch();
	}

	/**
	 * 网站配置管理
	 *
	 * @return mixed
	 * @throws \Exception
	 */
	public function group(){
		if($this->request->isPost()){
			$config = $this->request->param("config/a", []);

			if(SettingModel::load($config) === false){
				$this->error('保存失败！');
			}

			$this->success('保存成功！', Url::build("group"));
		}
		$id = $this->request->param('id/d', 1);
		$data = SettingModel::where('status', 1)->where('group', $id)->order('sort')->select();

		$this->assign('data', $data);
		$this->assign('id', $id);
		return View::fetch();
	}

	/**
	 * 配置排序
	 *
	 * @return mixed
	 * @throws ModelNotFoundException
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function sort(){
		if($this->request->isPost()){
			$idsGroup = $this->request->param("ids/a");
			foreach($idsGroup as $g => $ids){
				$ids = Str::explode($ids);
				foreach($ids as $k => $v){
					if(SettingModel::where('id', $v)->setField([
							"sort"  => $k,
							"group" => $g + 1,
						]) === false){
						$this->error("保存排序失败！");
					}
				}
			}
			$this->success("已更新排序！", $this->request->param("http_referer", 'index'));
		}

		$data = SettingModel::where('status', 1)->field('id,title,group')->order('sort asc')->select();
		$type = Config::get('web.config_group_list');
		$group = [];
		foreach($type as $k => $v){
			$group[$v] = [];
			/**@var $value \app\common\model\Setting */
			foreach($data as $key => $value){
				if($value->group == $k){
					unset($data[$key]);
					$group[$v][] = $value->toArray();
				}
			}
			unset($type[$k]);
		}
		$this->assign("group", $group);
		return View::fetch();
	}
}
